#include "KeyboardScene.hpp"
#include "core/Game.hpp"
#include "video/Screen.hpp"

namespace yep
{
KeyboardScene::~KeyboardScene()
{
}

void KeyboardScene::setup(Game& game)
{
    SDL_EnableUNICODE(true);
}

void KeyboardScene::cleanup(Game& game)
{
    SDL_EnableUNICODE(false);
}

void KeyboardScene::logic(Game& game)
{
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
        case SDL_QUIT:
            game.exit();
            break;
        case SDL_KEYDOWN:
            _lastPressedKey = event.key.keysym;
            break;
        }
    }
}

inline string toBin(Uint8 value)
{
    string result;
    for(int i=7; i>= 0; --i)
    {
        result += '0' | ((value>>i)&0x01);
    }
    return result;
}

void KeyboardScene::draw(Game& game)
{
    Screen &screen = Screen::getInstance();
    screen.fillRectangle({0,0}, Vector2(screen.getWidth(), 8), Color::RED);
    const string title = "KeyBoardTest";
    screen.drawText(Vector2((screen.getWidth()-8*title.size())/2, 0), Color::LIGHT_YELLOW, title);
    stringstream stream;
    stream << "KeyName : '" << SDL_GetKeyName(_lastPressedKey.sym) <<"'";
    screen.drawText({0,8}, Color::WHITE, stream.str());
    stream.str("");
    stream << "KeySym  : " << _lastPressedKey.sym;
    screen.drawText({0,16}, Color::WHITE, stream.str());
    stream.str("");
    stream << "Scancode: " << static_cast<unsigned>(_lastPressedKey.scancode);
    screen.drawText({0,24}, Color::WHITE, stream.str());
    stream.str("");
    stream << "Unicode : " << (char)_lastPressedKey.unicode;
    screen.drawText({0,32}, Color::WHITE, stream.str());
    stream.str("");
    stream << "Mod     : " << toBin(_lastPressedKey.mod);
    screen.drawText({0,40}, Color::WHITE, stream.str());
    stream.str("");
}

}
